import os
import json
import time
import stat




def Had(path):
    file_path = path

    if os.path.exists(file_path):
        return True
    else:
        return False


def Write(path, text):
    try:
        with open(path, 'w') as file:
            file.write(text)
        return True
    except Exception as e:
        return False


def Add(path, text):
    try:
        with open(path, 'a') as file:
            file.write(text)
        return True
    except Exception as e:
        return False


def Del(path):
    file_path = path
    # 检查文件是否存在
    if os.path.exists(file_path):
        # 删除文件
        os.remove(file_path)
        return True
    else:
        return False


def Read(path):
    if Had(path):
        with open(path, 'r') as f:
            file_content = f.read()
            return file_content
    else:
        return False


def SetAuthority(path, system):
    if system == "Windows":
        import win32file
        import win32security
        import ntsecuritycon

        # 获取管理员权限SID
        admins_sid = win32security.LookupAccountName("", "Administrators")[0]
        filename = path
        # 打开现有文件对象
        file_handle = win32file.CreateFile(
            filename,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
            None,
            win32file.OPEN_EXISTING,
            win32file.FILE_ATTRIBUTE_NORMAL,
            None
        )

        # 获取文件的安全描述符
        security_descriptor = win32security.GetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION)

        # 创建新的DACL，并添加允许访问的ACE
        dacl = win32security.ACL()
        dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, admins_sid)

        # 更新文件的安全描述符中的DACL
        security_descriptor.SetSecurityDescriptorDacl(1, dacl, 0)

        # 设置文件的安全描述符
        win32security.SetFileSecurity(filename, win32security.DACL_SECURITY_INFORMATION, security_descriptor)
    else:
        # 设置文件权限为root可读写，其它用户无法读写
        os.chmod(path, 0o600)


def get_file_info(path):
    file_info = {
        "type": None,
        "path": path,
        "name": os.path.basename(path),
        "auth": None,
        "size": None,
        "time": None
    }

    if os.path.isfile(path):
        file_info["type"] = "file"
        file_info["size"] = os.path.getsize(path)
    elif os.path.isdir(path):
        file_info["type"] = "folder"

    # Get permissions
    try:
        if os.name == 'nt':  # Windows
            import win32security
            security_info = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION)
            owner_sid = security_info.GetSecurityDescriptorOwner()
            file_info["auth"] = str(owner_sid)  # Convert PySID to string
        else:  # Unix/Linux
            file_info["auth"] = oct(os.stat(path).st_mode)[-3:]
    except Exception as e:
        file_info["auth"] = str(e)

    # Get last modified time
    try:
        file_info["time"] = time.ctime(os.path.getmtime(path))
    except Exception as e:
        file_info["time"] = str(e)

    return file_info


def get_directory_tree(root_path):
    directory_tree = []
    for item in os.listdir(root_path):
        item_path = os.path.join(root_path, item)
        directory_tree.append(get_file_info(item_path))

    # print(directory_tree)
    return directory_tree

"""path = "/your/path/here"
json_data = json.dumps(get_directory_tree(path), indent=4)
print(json_data)"""

